package com.tinem.platform.service.data.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.util.HttpMethod;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.module.pojo.vo.data.AreasRes;
import com.tinem.platform.module.pojo.vo.data.GetAreasInfoVO;
import com.tinem.platform.module.pojo.vo.data.GetProviceVO;
import com.tinem.platform.module.starter.jpa.entity.data.Areas;
import com.tinem.platform.module.starter.jpa.repository.data.AreasRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: platform
 * @description: ${description} 行政区划服务
 * @author: eden#can
 * @Slogan: 没有所谓失败，除非你不再尝试
 * @date: 2021-12-28 13:56
 **/
@Slf4j
@Api(value = "areas")
@RestController
@RequestMapping("/areas")
public class AreasApi {

    @Resource
    AreasRepository areasRepository;

    @Resource
    HttpServletRequest request;

    @PostMapping("/getProvice.api")
    @ResponseBody
    @ApiOperation(value = "获取行政区列表接口", httpMethod = HttpMethod.POST, notes = "暂无")
    public List<Areas> getProvice(@Validated @RequestBody GetProviceVO req){

        String lang = request.getHeader(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_LANG);

        log.info("获取行政区列表接口 getProvice req JSON:{},Lang:{}", JSONUtil.toJsonStr(req),lang);

        List<Areas> list;
        if(StrUtil.isNotBlank(req.getCountryId())){
            list = areasRepository.findByLangIdAndParentIdOrderBySortAsc(lang, req.getCountryId());
        } else {
            list = areasRepository.findByLangIdOrderBySortAsc(lang);
        }
        return list;
    }

    @PostMapping("/getAreasInfo.api")
    @ResponseBody
    @ApiOperation(value = "获取行政区信息接口", httpMethod = HttpMethod.POST, notes = "暂无")
    public AreasRes getAreasInfo(@Validated @RequestBody GetAreasInfoVO req){

        log.info("获取行政区列表接口 getAreasInfo req JSON:{}", JSONUtil.toJsonStr(req));

        Areas areas = areasRepository.findByLangIdAndParentIdAndSId(
                req.getLangId(),req.getParentId(),req.getAreasSid());
        if(areas != null){
            AreasRes areasRes = new AreasRes();
            BeanUtil.copyProperties(areas,areasRes);
            return areasRes;
        }
        return  null;
    }


    @PostMapping("/getCountrys.api")
    @ResponseBody
    @ApiOperation(value = "获取国家列表接口", httpMethod = HttpMethod.POST, notes = "暂无")
    public List<Areas> getCountrys(HttpServletRequest request){

        String lang = request.getHeader(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_LANG);

        log.info("获取国家列表接口 getCountrys req Lang:{}",lang);

        return areasRepository.findByLangIdAndParentIdOrderBySortAsc(lang, "1");
    }

    /**
     * 将数据库中所有行政区域信息转化成json
     * @param request
     * @return
     */
    @PostMapping("/getAll.api")
    @ResponseBody
    @ApiOperation(value = "获取所有行政区域信息", httpMethod = HttpMethod.POST, notes = "暂无")
    public List<Object> getAll(HttpServletRequest request){
        List<Areas> areas = areasRepository.findAll();
        JSONObject areaJsonMap = new JSONObject();
        JSONObject areaJsonMapList = new JSONObject();
        areas.forEach(a->{
            if(!areaJsonMap.containsKey(a.getSId())){
                JSONObject areaJsonObject = new JSONObject();
                areaJsonObject.put("id",a.getSId());
                areaJsonObject.put("sort",a.getSort());
                areaJsonObject.put("parentId",a.getParentId());
                areaJsonMap.put(a.getSId(),areaJsonObject);
                if(!areaJsonMapList.containsKey(a.getParentId())){
                    areaJsonMapList.put(a.getParentId(),new JSONArray());
                }
                areaJsonMapList.getJSONArray(a.getParentId()).add(areaJsonObject);
            }
            JSONObject areaJsonObject = areaJsonMap.getJSONObject(a.getSId());
            if(a== null || StrUtil.isEmpty(a.getLangId()) || StrUtil.isEmpty(a.getName())){
                return;
            }
            if(areaJsonObject.getInteger("sort") < a.getSort()){
                areaJsonObject.put("sort",a.getSort());
            }
            areaJsonObject.put("sort_"+a.getLangId(),a.getSort());
            areaJsonObject.put(a.getLangId(),a.getName());

        });
        List res =  areaJsonMap.keySet().stream().map(a->{
            if(areaJsonMapList.containsKey(a)){
                areaJsonMap.getJSONObject(a).put("children",areaJsonMapList.get(a));
            }
           return areaJsonMap.get(a);
        }).filter(a->"1".equals(((JSONObject)a).getString("parentId")))
                .collect(Collectors.toList());
        return res;
    }
}
